/**
 * @description: 组合商品添加商品弹框
 * @author: elvis
 */

import { useState } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import CommonTable from '@/components/CommonTable';
import CommonPagination from '@/components/CommonPagination';
import FuzzyQueryStore from '@/components/FuzzyQueryStore';
import DynamicStoreSelect from '@/components/DynamicStoreSelect';
import CommonZjfImg from '@/components/CommonImg/ZifComponent';
import CommonSysImg from '@/components/CommonImg/SysComponent';
import CommonPlatImg from '@/components/CommonImg/PlatformComponent';
import { queryShopGoodsList, queryGoodsListNew, querySysGoodsList } from '@/services/common';
import { formatZjfImg, openUrl, customTrimFunc, formatAmount } from '@/utils/utils.jsx';
import { findIndex } from 'lodash';
import { Button, Form, Input, message, Select, InputNumber } from 'antd';
import CommonTag from '@/components/CommonTag';

const { Option } = Select;

//type根据matchType传参
const typeMap = {
    0: 1,
    1: 2,
    3: 3,
}

export default ({ visible, item, handleOk, handleCancel }) => {
	//商品列表
	const [goodsList, setGoodsList] = useState([]);

	const [form] = Form.useForm();

	//查询维度，默认为供应商
	const [type, setType] = useState(1);

	//列表分页
	const [pages, setPages] = useState({
		current: 1,
		total: 0,
		pageSize: 10,
		showSizeChanger: false,
	});

	//表单搜索
	const [query, setQuery] = useState({});

	//选中行id
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);

	//选中行
	const [selectedRows, setSelectedRows] = useState([]);

	const [loading, setLoading] = useState(false);

	const [resetKey, setResetKey] = useState(0);

	//查询商品
	const getGoodsList = async (query, page) => {
		setLoading(true);
		//请求参数过滤前后空格
		const params = customTrimFunc({
			...query,
			current: page.current,
			size: page.pageSize,
			isRemoveCombinati: 2,
		});

		if (type == 1) {
			const { data, success } = await queryGoodsListNew(params);
			if (success) {
				const { records, total } = data;
				if(records.length > 0) {
					const arr = records.map(v => v.goodsId);
					const res = await queryShopGoodsList({
						ids: arr.join(','),
					});
					if (res.success) {
						setGoodsList(res.data);
						setPages({ ...page, total });
						setSelectedRows([]);
						setSelectedRowKeys([]);
					}
				} else {
					setGoodsList([]);
					setSelectedRows([]);
					setSelectedRowKeys([]);
				  setPages({ ...page, total: 0 });
				}
			}else{
				setGoodsList([]);
				setPages({ ...page, total: 0 });
			}
		} else {
			const { data, success } = await querySysGoodsList(params);
			if (success) {
				const { records = [], total } = data;
				setGoodsList(records);
				setPages({ ...page, total });
				setSelectedRows([]);
				setSelectedRowKeys([]);
			}
		}
		setLoading(false);
	};

	//点击确定
	const onOk = () => {
		if (selectedRows.length > 0) {
			//此处做一些处理
			const arr = [];
			if(type == 1) {//供应商维度
				for(let i in selectedRows) {
					let obj  = {};
					const obj1 = selectedRows[i];
					if(obj1.platformGoods.id) {//代表已匹配
						if(obj1.platformGoods.deliverType == 3) {
							//已匹配的库存商品展示网店商品
							obj = { ...obj1.platformGoods, goodsNum: 1, type: 2, productId: obj1.platformGoods.id, productType: 2, customType: 'shop', storeId: obj1.matchingGoods.storeId, goodsId: obj1.matchingGoods.goodsId, goodsCommonId:  obj1.matchingGoods.goodsCommonId }
						} else {
							obj = { ...obj1.matchingGoods, goodsNum: 1, type: 2, productId: obj1.platformGoods.id, productType: 2, customType: 'zjf', deliverType: obj1.platformGoods.deliverType }
						}
					} else {
						obj = { ...obj1.matchingGoods, goodsNum: 1, type: 2, productId: 0, productType: 2, customType: 'zjf' }
					}
					arr.push(obj);
				}
			} else {//系统维度
				for(let i in selectedRows) {
					let obj = {};
					const obj1 = selectedRows[i];
					if(obj1.matchingGoods.goodsId) {//代表已匹配
						if(obj1.sysformGoods.deliverType != 3) {//非库存
							obj = { ...obj1.matchingGoods, goodsNum: 1, type: typeMap[obj1.sysformGoods.matchType], productId: obj1.sysformGoods.id, productType: 1, customType: 'zjf', deliverType: obj1.sysformGoods.deliverType, price: obj1.sysformGoods.matchType == 3 ? obj1.matchingGoods.goodsPrice: undefined };
						} else {
							obj = { ...obj1.sysformGoods, goodsId: obj1.matchingGoods.goodsId, goodsCommonId: obj1.matchingGoods.goodsCommonId, storeId: obj1.matchingGoods.storeId, goodsNum: 1, type: typeMap[obj1.sysformGoods.matchType], productId: obj1.sysformGoods.id, productType: 1, customType: 'sys', price: obj1.sysformGoods.matchType == 3 ? obj1.matchingGoods.goodsPrice: undefined };
						}
					} else {
						obj = { ...obj1.sysformGoods, goodsNum: 1, type: typeMap[obj1.sysformGoods.matchType], productId: obj1.sysformGoods.id, productType: 1, customType: 'sys' };
					}
					arr.push(obj);
				}
			}
			handleOk(arr);
		} else {
			message.info('未选中商品');
		}
	};

	//查询
	const onFinish = (val) => {
		setQuery(val);
		getGoodsList(val, { ...pages, current: 1 });
	};

	//重置
	const onReset = () => {
		form.resetFields();
		setQuery({});
		setGoodsList([]);
		setPages({ ...pages, current: 1, total: 0 });
		setSelectedRows([]);
		setSelectedRowKeys([]);
		setResetKey(resetKey + 1);
	};

	//更改查询类型
	const handleChangeType = val => {
		setQuery({});
		setGoodsList([]);
		setPages({ ...pages, current: 1, total: 0 });
		setSelectedRowKeys([]);
		setSelectedRows([]);
		setType(val);
		form.setFieldsValue({
			storeIds: undefined
		})
	}

	const columns = [
		{
			title: '网店/系统商品名称',
			dataIndex: 'goodsName',
			key: 'goodsName',
			width: '35%',
			render: (_, record) => {
				if(type == 1) {
					const obj = record.platformGoods;
					if(Object.keys(obj).length > 0) {
						return (
							<div style={{ display: 'flex', alignItems: 'center' }}>
								<CommonPlatImg img={obj.ecGoodsImage}  style={{ marginRight: '8px' }} />
								<div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
									<span>{obj.ecGoodsName}{obj.ecSkuName}</span>
									<span className="common-color9">¥{formatAmount(obj.ecGoodsPrice)}</span>
                                    <span>商品编码：{obj.outStoreSku}</span>
									<span>
										{ (obj.deliverType == 1 || obj.deliverType == 2)  && <CommonTag type='nahuo' /> }
										{ obj.deliverType == 3 && <CommonTag type='zifa' /> }
										{ obj.deliverType == 4 && <CommonTag type='cjzf' /> }
									</span>
								</div>
							</div>
						);
					}
					return null;
				} else {
					const obj = record.sysformGoods;
					if(Object.keys(obj).length > 0) {
						return (
							<div style={{ display: 'flex', alignItems: 'center' }}>
								<CommonSysImg img={obj.goodsImage} isCloudIcon={obj.isCarefullySelected} storeId={obj.storeId}  style={{ marginRight: '8px' }} />
								<div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
									<span>{obj.goodsName}{obj.skuName}</span>
									<span className="common-color9">¥{formatAmount(obj.goodsPrice)}</span>
                                    <span>商品编码：{obj.skuId}</span>
									<span>
										{ (obj.deliverType == 1 || obj.deliverType == 2) && <CommonTag type='nahuo' /> }
										{ obj.deliverType == 3 && <CommonTag type='zifa' /> }
										{ obj.deliverType == 4 && <CommonTag type='cjzf' /> }
									</span>
								</div>
							</div>
						);
					}
					return null;
				}
			},
		},
		{
			title: '匹配状态',
			dataIndex: 'goodsImage',
			key: 'goodsImage',
			render: (_, record) => {
				if(type == 1) {
					if(record.platformGoods.matchType && record.platformGoods.matchType >  0)  {
						return '已匹配 ';
					} else {
						return '未匹配';
					}
				} else {
					if(record.sysformGoods.matchType && record.sysformGoods.matchType >  0)  {
						return '已匹配 ';
					} else {
						return '未匹配';
					}
				}
			},
		},
		{
			title: '供应商商品名称',
			dataIndex: 'matchingGoods',
			key: 'matchingGoods',
			width: '35%',
			render: (text, record) => {
                let obj = record?.platformGoods || record?.sysformGoods;;
				if(Object.keys(text).length > 0) {
					return (
						<div style={{ display: 'flex', alignItems: 'center' }}>
							<CommonZjfImg img={text.goodsImage} isCloudIcon={text.isCarefullySelected} storeId={text.storeId}  style={{ marginRight: '8px' }} />
							<div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
								<span>{text.goodsName}{text.goodsSpec}</span>
								<span className="common-color9">¥{text.vipPrice?formatAmount(text.vipPrice):formatAmount(text.goodsPrice)}</span>
                                {
                                    obj.matchType == '3' ? 
                                 <div style={{display: 'flex'}}><span>商品编码：</span><span className='textOverflowMultiOne'>{obj?.outStoreSku || obj?.skuId}</span></div>
                                 :
                                 <div style={{display: 'flex'}}><span>商品编码：</span><span className='textOverflowMultiOne'>{text.goodsId}</span></div>
                                }
								<span>
									{ (text.deliverType == 1 || text.deliverType == 2)  && <CommonTag type='nahuo' /> }
									{ text.deliverType == 3 && <CommonTag type='zifa' /> }
									{ text.deliverType == 4 && <CommonTag type='cjzf' /> }
								</span>
							</div>
						</div>
					);
				}
				return null;
			},
		},
		{
			title: '供应商',
			dataIndex: 'storeName',
			key: 'storeName',
			render: (_, record) => {
				return <span className="table-weight-text">{record.matchingGoods.storeName}</span>;
			},
		},
	];

	const pageProps = {
		pagination: pages,
		handleChange(current, size) {
			const obj = { ...pages, current, pageSize: size };
			setPages(obj);
			getGoodsList(query, obj);
		},
	};

	//表格
	const TableProps = {
		columns,
		data: goodsList,
		handleRowKey(record) {
			if(type == 1) {
				return record.matchingGoods.goodsId + record.platformGoods.id;
			} else {
				return record.sysformGoods.id;
			}
		},
		scroll: { y: 400 },
		rowSelection: {
			type: 'checkbox',
			fixed: true,
			selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				setSelectedRowKeys(selectedRowKeys);
				setSelectedRows(selectedRows);
			},
		},
	};

	//供应商公共组件
	const dynamicStoreSelectProps = {
		resetKey,
		styles: {width:'180px', marginRight:'8px'},
    handleAllSelect(storeIds){
      form.setFieldsValue({ storeIds })
    }
  }

	return (
		<CommonModal
			title="添加商品"
			visible={visible}
			onOk={onOk}
			onCancel={handleCancel}
			width="1060px"
			overflowY='hidden'
		>
			<Form
				layout={'inline'}
				className="search-form-style"
				form={form}
				onFinish={onFinish}
				style={{ marginBottom: '12px' }}
				name="combind-add-goods"
			>
				<Form.Item style={{marginRight:'12px'}}>
					<Select style={{ width: '120px' }} value={type} onChange={handleChangeType}>
						<Option value={1}>供应商维度</Option>
						<Option value={2}>系统商品维度</Option>
					</Select>
				</Form.Item>
				{
					type == 1 &&
					<>
					  <DynamicStoreSelect {...dynamicStoreSelectProps} />
						{/* <Form.Item
							label="供应商"
							name="storeId"
							rules={[{ required: true, message: '请先输入检索供应商' }]}
						>
							<FuzzyQueryStore style={{ width: '120px' }} />
						</Form.Item> */}
						<Form.Item label="供应商商品名称" name="goodsName">
							<Input placeholder="请输入商品名称" style={{ width: '120px' }} />
						</Form.Item>
						<Form.Item label="商品编码" name="goodsId">
							<InputNumber placeholder="请输入商品编码" style={{ width: '120px' }} />
						</Form.Item>
					</>
				}
				{
					type == 2 &&
					<>
						<Form.Item label="系统商品名称" name="goodsName">
							<Input placeholder="请输入系统商品名称" style={{ width: '360px' }} />
						</Form.Item>
					</>
				}
				<Form.Item>
					<Button type="primary" htmlType="submit" style={{ marginRight: '16px' }}>
						查询
					</Button>
					<Button onClick={onReset}>重置</Button>
				</Form.Item>
			</Form>
			<CommonTable {...TableProps} />
			<div style={{ height: 28, marginTop: '12px', textAlign: 'right' }}>
				<CommonPagination {...pageProps} />
			</div>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};
